layui.use(['layer','form','upload'], function() {
    var layer = layui.layer, form = layui.form,upload = layui.upload;
    var fileObj = {docId:'temp_'+uuid(), docType:'exp_order'};
    $('.sel-load').selLoad(function () {
        form.render('select');
        var id = getUrlParam("id"),isCopy = isNotEmpty(getUrlParam("copy"));
        if(isEmpty(id)){
            // 新增
            generateDocNo(); //生成单号
            createRow();//创建一行空的明细
            $("#orderDate").val(getNowFormatDate());
            // 获取默认报关模板信息
            show_loading();
            $.get('/scm/declarationTemp/expDefault',{},function (res){
                if(isSuccess(res)){
                    var data = res.data;
                    if(isEmpty(data)){
                        data = {'currencyName':'美元'}
                    }else{
                        data['districtCode'] = data['districtCode'];
                        data['districtCodeName'] = data['districtName'];
                        data['cusTradeCountry'] = data['cusTradeCountryCode'];
                        data['cusTradeCountryName'] = data['cusTradeCountryName'];
                        data['cusTradeNationCode'] = data['cusTradeNationCode'];
                        data['cusTradeNationCodeName'] = data['cusTradeNationName'];
                        data['distinatePort'] = data['distinatePortCode'];
                        data['distinatePortName'] = data['distinatePortName'];
                        data['cusTrafMode'] = data['cusTrafModeCode'];
                        data['destinationCountry'] = data['destinationCountry'];
                        data['destinationCountryName'] = data['destinationCountryName'];
                    }
                    data['currencyName'] = '美元';
                    if(isEmpty(data['districtCode'])) {
                        data['districtCode'] = '44031';
                        data['districtCodeName'] = '深圳特区';
                    }
                    //id清空否则会被当做订单id
                    data['id'] = null;
                    form.val('orderMainForm',data);
                }
            });
            $("#transactionMode").val("fob");
            app.obtainSubject(function (sub) {
                $('#subjectName').val(sub['name']);
                $('#subjectId').val(sub['id']);
            });
        }else{
            if(!isCopy){
                fileObj.docId = id;
            }
            $.post(rurl('scm/expOrder/detail'),{'id':id,'operation':isCopy?'':'exp_order_edit'},function (res) {
                if(isSuccessWarnClose(res)){
                    let data = res.data,order=data.order,logistiscs=data.logistiscs;
                    if(isCopy){
                        order.id = "";// 订单ID
                        order.docNo = "";// 订单号
                        // order.clientNo = "";// 客户单号
                        order.orderDate = getNowFormatDate();
                    }
                    form.val('orderMainForm',order);
                    oldCustomerId = order.customerId;
                    //获取客户协议报价
                    obtainAgreement(order.customerId,order.agreementId);
                    $('#memo').val(order.memo);
                    if(!isCopy){
                        $('#customerName').hide();
                        $('#customerNameEdit').val(order.customerName).show();
                    }else{
                        generateDocNo(); //生成单号
                    }
                    // 产品明细
                    if(!isCopy) {
                        createRows(data.members);
                    } else {
                        createRows();
                    }
                    // 物流信息
                    if(isNotEmpty(logistiscs.isCharterCar)){
                        logistiscs.isCharterCar = logistiscs.isCharterCar.toString();
                    }
                    form.val('orderLogisticsForm',logistiscs);
                    //获取国内交货信息
                    takeDeliveryInformation(order.customerName,logistiscs.customerDeliveryInfoId);
                    //获取境外交货送货信息
                    takeInformation(order.customerName,logistiscs.supplierTakeInfoId);
                    // 国内交货方式
                    showOrHide($('#deliveryMode'));
                    // 境外交货信息展示
                    initOverseasDelivery();
                    // 外贸合同买方
                    initBuyerType();
                }
            });
        }
        autoCurrency();  //币制填充
        //初始化附件
        $('.file-size').attr({'doc-id':fileObj.docId});
        initFileSize();
        //监听交货方式
        form.on('select(deliveryMode)', function(da){showOrHide($(da.elem));});
        //监听是否包车
        form.on('radio(isCharterCar)', function(da){
            initOverseasDelivery();
        });
        //监听送货目的地
        form.on('radio(deliveryDestination)', function(da){
            initOverseasDelivery();
        });
        //监听外贸合同买方
        form.on('radio(subjectOverseasType)', function(da){
            initBuyerType();
        });
    });
    $('.save-btn').click(function () {saveExpOrder(false,fileObj);});
    $('.examine-btn').click(function () {saveExpOrder(true,fileObj);});

    upload.render({
        elem: '#importExcel',url:rurl('scm/expOrder/importMember'),size:10240,exts:'xls|xlsx'
        ,acceptMime:'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ,before:function (res) {
            show_loading();
        },done: function(res){
            if(isSuccessWarn(res)){
                var memberData = res.data;
                show_msg("成功解析："+memberData.length+" 条数据");
                $('input[name="model"]').each(function (i,o) {
                    var $model = $(o);if(isEmpty($model.val())){
                        $model.parent().parent().remove();
                    }
                });
                createRows(memberData);
                calculationAll();
            }
        },error:function (index, upload) {
            hide_loading();
        }
    });

});
function saveExpOrder(submitAudit,fileObj) {
    if(!checkedForm($('#orderMainForm'))){return;}
    var order = $('#orderMainForm').serializeJson(),logistiscs =  $('#orderLogisticsForm').serializeJson(),members = obtainMenberJSON();
    order['memo'] = $('#memo').val();//备注
    postJSON('scm/expOrder/'.concat(isEmpty(order.id)?'add':'edit'),{"order":order,"logistiscs":logistiscs,"members":members,"file":fileObj,"submitAudit":submitAudit},function (res) {
        parent.reloadList();
        closeThisWin('保存成功');
    });
}
$('#addSupplier').click(function () {
    var mid=parent.parent.obtainMIdByOperation('supplier_list'),taskArg={"documentId":"","documentClass":"","operation":"supplier_add"};
    if(isEmpty(mid)){prompt_warn('对不起您无此权限,请联系贵司管理员授权!');return;}
    setLocalStorage('TASK_'+mid,JSON.stringify({"customerName":$('#customerName').val()}));
    setLocalStorage('AUTO_TASK',JSON.stringify(taskArg));
    parent.parent.refreshTab(mid);
});
$('#addCustomerSubjectOverseasName').click(function () {
    var mid=parent.parent.obtainMIdByOperation('supplier_list'),taskArg={"documentId":"","documentClass":"","operation":"supplier_add"};
    if(isEmpty(mid)){prompt_warn('对不起您无此权限,请联系贵司管理员授权!');return;}
    setLocalStorage('TASK_'+mid,JSON.stringify({"customerName":$('#customerName').val()}));
    setLocalStorage('AUTO_TASK',JSON.stringify(taskArg));
    parent.parent.refreshTab(mid);
});

